package com.xyzh05.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.service.DictManager;
import com.xyzh05.model.Dict;
import com.xyzh05.webapp.action.BaseAction;

import java.util.List;

public class DictAction extends BaseAction implements Preparable {
    private DictManager dictManager;
    private List dicts;
    private Dict dict;
    private Long id;
    private String query;

    public void setDictManager(DictManager dictManager) {
        this.dictManager = dictManager;
    }

    public List getDicts() {
        return dicts;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String dictId = getRequest().getParameter("dict.id");
            if (dictId != null && !dictId.equals("")) {
                dict = dictManager.get(new Long(dictId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        dicts = dictManager.search(query, Dict.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Dict getDict() {
        return dict;
    }

    public void setDict(Dict dict) {
        this.dict = dict;
    }

    public String delete() {
        dictManager.remove(dict.getId());
        saveMessage(getText("dict.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            dict = dictManager.get(id);
        } else {
            dict = new Dict();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (dict.getId() == null);

        dictManager.save(dict);

        String key = (isNew) ? "dict.added" : "dict.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}